﻿Imports System
Imports System.IO
Imports System.Configuration
Imports System.Data.SqlClient

Public Class DataWriter
    Private _SyncID As Integer

    Public Property SyncID As Integer
        Get
            SyncID = _SyncID
        End Get
        Set(ByVal value As Integer)
            _SyncID = value
        End Set
    End Property

    Public Sub New(ByVal SyncID As Integer)
        _SyncID = SyncID
    End Sub

    ''' <summary>
    ''' Updates the sync metadata in the database sync table.
    ''' </summary>
    ''' <remarks>Sync metadata should be updated at the end of every successful transmission to the hub.</remarks>
    Public Sub UpdateSyncMetadata(ByVal LastRecordDateTime As String, ByVal Response As String)
        'TODO: This could be more robust, but for now I just want to get it working

        'TODO: This needs to be changed to just notify the user that it failed and keep it enabled.
        If Not Response.Contains("success") Then
            'TODO: I don't need to set this back, just use the original LRDT
            LastRecordDateTime = "1/1/1900 00:00:00"

            'try sending an email
            Try
                Dim mailer As New NotifyMail()
                mailer.SendServiceMail("VOEIS Hub Push Service - Upload Failure", "Error uploading data file to the hub: " & Environment.NewLine & Response)
            Catch ex As Exception
                System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service", "Error sending mail from the DataWriter class after push failure." & Environment.NewLine & ex.Message.ToString, EventLogEntryType.Error)
            End Try
        End If

        'TODO: I need to genericize the call to the connection string
        Dim escResponse As String = Response.Replace("'", "''")
        Dim cmdTxt As String = "EXEC dbo.usp_UpdateSyncMetadata " & SyncID.ToString & ",'" & LastRecordDateTime & "','" & escResponse & "'"
        Dim conn As New SqlConnection(DataMonitor.SetConnectionString())
        Dim cmd As New SqlCommand(cmdTxt, conn)
        Dim rowsAffected As Integer

        Try
            'Open the database connection and execute our statement
            conn.Open()

            rowsAffected = cmd.ExecuteNonQuery()

            'TODO: I'm not getting a return value as expected and this throws an error every time even if there isn't an error
            If rowsAffected < 1 Then
                Throw New ArgumentOutOfRangeException
            End If

        Catch AOORex As ArgumentOutOfRangeException
            'We're here because we didn't update any rows
            System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service", "No rows updated after running the command 'EXEC dbo.usp_UpdateSyncMetadata'." & Environment.NewLine & "Rows Returned: " & rowsAffected.ToString, EventLogEntryType.Error)
        Catch ex As Exception
            'We're here because something bad happened
            System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service", "Error in DataWriter class." & Environment.NewLine & ex.Message.ToString, EventLogEntryType.Error)

            'Email the exception and setup the current state
            Dim mailer As New NotifyMail()
            mailer.SendServiceMail("VOEIS Hub Push Service - Error", "Error in DataWriter class." & Environment.NewLine & ex.Message.ToString)
        Finally
            conn.Close()
        End Try
    End Sub

    ''' <summary>
    ''' Changes the sync item's enabled status depending on the input value
    ''' </summary>
    ''' <param name="Enabled"></param>
    ''' <remarks>Sync items should be disabled at the beginning of the push and re-enabled at the end of the push</remarks>
    Public Sub UpdateStreamStatus(ByVal Enabled As Boolean)
        Dim cmdTxt As String = "EXEC dbo.usp_UpdateStreamStatus " & SyncID.ToString & ", " & Enabled.ToString
        Dim conn As New SqlConnection(DataMonitor.SetConnectionString())
        Dim cmd As New SqlCommand(cmdTxt, conn)
        Dim rowsAffected As Integer

        Try
            'Open the database connection and execute our statement
            conn.Open()

            rowsAffected = cmd.ExecuteNonQuery

            If rowsAffected < 1 Then
                Throw New ArgumentOutOfRangeException
            End If

        Catch AOORex As ArgumentOutOfRangeException
            System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service", "No rows updated after running the commannd 'EXEC dbo.usp_UpdateStreamStatus'." & Environment.NewLine & "Rows Returned: " & rowsAffected.ToString, EventLogEntryType.Error)

        Catch ex As Exception
            System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service", "Error in DataWriter class." & Environment.NewLine & ex.Message.ToString, EventLogEntryType.Error)

            'Email the exception and setup the current state
            Dim mailer As New NotifyMail()
            mailer.SendServiceMail("VOEIS Hub Push Service - Error", "Error in DataWriter class." & Environment.NewLine & ex.Message.ToString)
        Finally
            conn.Close()

        End Try
    End Sub
End Class
